import java.io.IOException;
import java.net.*;
import java.util.Stack;

public class DatagramServer {
	private final static int PACKETSIZE = 100;

	public static void main(String args[]) {
		// Check the arguments
		if (args.length != 1) {
			System.out.println("usage: DatagramServer port");
			return;
		}
		// Convert the argument to ensure that is it valid
		int port = Integer.parseInt(args[0]);
		// Construct the socket
		DatagramSocket socket = null;
		DatagramPacket packet = null;
		try {
			socket = new DatagramSocket(port);
		} catch (SocketException e2) {
			// TODO Auto-generated catch block
			e2.printStackTrace();
		}
		StackImpl stack = new StackImpl();
		String item = null;
		for (;;) {
			try {
				System.out.println("The server is ready...");
				// Create a packet
				packet = new DatagramPacket(new byte[PACKETSIZE], PACKETSIZE);
				// Receive a packet (blocking)
				socket.receive(packet);
				// Print the packet

//				System.out.println(packet.getAddress() + " " + packet.getPort()
//						+ ": " + new String(packet.getData()));
				String data = new String(packet.getData()).trim();
				if (data.equals("pop")) {					
					item = stack.pop().toString();
				} else if (data.equals("push")) {
					System.out.println("Ready to PUSH");
					packet = new DatagramPacket(new byte[PACKETSIZE], PACKETSIZE);
					socket.receive(packet);
					item = new String(packet.getData());					
					stack.push(item.trim());
					System.out.println("Pushed : "+item.toString());
				} else if(data.equals("print")){
					item = stack.toString();		
					if(item == null){
						item = "Empty Stack !!";
					}
					
				}
				// Return the packet to the sender
				packet.setData(item.getBytes());
				socket.send(packet);

			} catch (SocketException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (StackException e) {
				try {
					if (e.getExceptionType() == -1) {
						packet.setData("underflow".getBytes());
						socket.send(packet);
					} else if (e.getExceptionType() == -2) {
						packet.setData("overflow".getBytes());
						socket.send(packet);
					}
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			}
		}
	}
}